package com.hxkj.controller;

import com.hxkj.client.service.*;
import com.hxkj.domain.enums.UserExceptionEnum;
import com.hxkj.domain.po.*;
import com.hxkj.domain.result.UserParameterDataStruct;
import com.hxkj.domain.vo.SysCooperationVO;
import com.hxkj.entity.vo.WebsiteAddrDetail;
import com.hxkj.service.TokenService;
import com.hxkj.service.UserSiteCollectService;
import com.platform.common.domain.exception.CustomException;
import com.platform.common.domain.exception.CustomMessageException;
import com.platform.common.domain.result.ResultDataStruct;
import com.platform.common.domain.result.ResultMessageStruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * created by kezhijie on 2018/8/31 15:09.
 * email to kezhijie@hxoss.com
 */
@RestController
@RequestMapping("userinfo")
public class UserInfoController {

    @Autowired
    private UserInfoServiceClient userInfoServiceClient;

    @Autowired
    private SysNavigatesServiceClient snsClient;
    @Autowired
    private UserSiteCollectService userSiteCollectService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private UserCenterServiceClient userCenterServiceClient;
    @Autowired
    private SysCooperationServiceClient cooperationServiceClient;
    @Autowired
    private SystemMessageReceiveServiceClient receiveServiceClient;
    @Autowired
    private MessageServiceClient messageServiceClient;
    @Autowired
    private SiteServiceClient siteServiceClient;
    @Autowired
    private WebsiteAddrServiceClient websiteAddrServiceClient;
    @Autowired
    private UserFootprintServiceClient userFootprintServiceClient;
    @Autowired
    private UniversalServiceClient universalServiceClient;
    @Autowired
    private CertExpertServiceClient certExpertServiceClient;
    @Autowired
    private CertOrgsServiceClient certOrgsServiceClient;

    @Value("${storage.imgUrl}")
    private String imgIPPORT;

    @GetMapping("get")
    public Map<String, Object> get(HttpServletRequest request) throws Exception {
        String accessToken = request.getHeader("accessToken");

        Token token = tokenService.validate(accessToken).getData();
        String userId = token.getUserId();

        if (StringUtils.isEmpty(accessToken))
            throw new CustomException(UserExceptionEnum.TOKEN_NOT_EXIST);

        ResultDataStruct<SysUser> resultDataStruct = userInfoServiceClient.userinfoGet(accessToken);
        if (resultDataStruct.getCode() == 500)
            throw new CustomMessageException(resultDataStruct.getMessage());
        if (resultDataStruct.getCode() != 200)
            throw new CustomException(UserExceptionEnum.getEnumByCode(resultDataStruct.getCode()));

        ResultDataStruct<List<SysNavigates>> result = snsClient.select();
        if(result.getCode() != 200)
            throw new CustomMessageException(result.getMessage());

        List<WebsiteAddrDetail> websiteAddrDetails = userSiteCollectService.collectList(userId);

        ResultDataStruct<SysCooperationVO> resultCoo = cooperationServiceClient.getSysCooperationForFront();
        if(resultCoo.getCode() != 200)
            throw new CustomMessageException(resultCoo.getMessage());

        int unReadSysMsg = receiveServiceClient.getUnReadMessageCount(userId);
        int unReadSiteMsg = messageServiceClient.getUnReadCount(userId);
        int totalUnReadMsg = unReadSysMsg + unReadSiteMsg;

        Map<String, Object> map = new HashMap<>();
        map.put("user",resultDataStruct.getData());
        map.put("menus",result.getData());
        map.put("collectList", websiteAddrDetails);
        map.put("cooperation",resultCoo.getData());
        map.put("totalUnReadMsg",totalUnReadMsg);
        map.put("unReadSysMsg",unReadSysMsg);
        map.put("unReadSiteMsg",unReadSiteMsg);

        // 添加认证信息
        CertExpert certExpert = certExpertServiceClient.getByUserId(userId).getData();
        map.put("certify", null); // 保证数据结构完整性
        if (Objects.isNull(certExpert)) {
            CertOrgs certOrgs = certOrgsServiceClient.getByUserId(userId).getData();

            if (Objects.nonNull(certOrgs) && certOrgs.getStatus().equals("10"))
                map.put("certify", certOrgs.getOrgName()); // 机构认证取机构名称
        } else {
            if (certExpert.getStatus().equals("10"))
                map.put("certify", certExpert.getPosition()); // 专家认证取专家认证资质
        }

        return map;
    }

    /**
     * 提供给除用户中心外站点获取用户信息，同时记录用户访问站点。
     * @param siteId 站点ID
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "getUserInfo", method = {RequestMethod.POST,RequestMethod.OPTIONS})
    public SysUser getUserInfo(Long siteId, HttpServletRequest request) throws Exception {
        String accessToken = request.getHeader("accessToken");
        SysUser sysUser = userInfoServiceClient.userinfoGet(accessToken).getData();

        Site siteCondition = new Site();
        siteCondition.setSiteId(siteId);
        Site siteInfo = siteServiceClient.getSite(siteCondition).getData();
        SiteUniversal siteUniversalCondition = new SiteUniversal();
        siteUniversalCondition.setSiteId(siteId);
        SiteUniversal siteUniversalInfo = universalServiceClient.get(siteUniversalCondition).getData();
        String logo = imgIPPORT + siteUniversalInfo.getLogo2();

        WebsiteAddr websiteAddrCondition = new WebsiteAddr();
        websiteAddrCondition.setSiteId(siteId);
        List<WebsiteAddr> websiteAddrs = websiteAddrServiceClient.getList(websiteAddrCondition);
        WebsiteAddr websiteAddrInfo = new WebsiteAddr();
        if (websiteAddrs.size() > 0)
            websiteAddrInfo = websiteAddrs.get(0);
        else
            throw new CustomMessageException("站点信息配置有误，请检查站点配置");

        // 拼接URL
        StringBuilder urlBuild = new StringBuilder();
        if (StringUtils.hasText(websiteAddrInfo.getIpAdd())){
            urlBuild.append(websiteAddrInfo.getIpAdd());
            if (StringUtils.hasText(websiteAddrInfo.getIpPort()))
                urlBuild.append(":").append(websiteAddrInfo.getIpPort());
        }

        // 按照规则，去掉网站配置的前缀
//        if (StringUtils.hasText(websiteAddrInfo.getUrlPrefix())){
//            if (websiteAddrInfo.getUrlPrefix().startsWith("/")) {
//                urlBuild.append(websiteAddrInfo.getUrlPrefix());
//            } else {
//                urlBuild.append("/").append(websiteAddrInfo.getUrlPrefix());
//            }
//        }

        // 记录用户足迹
        String url = urlBuild.toString();

        UserFootprint userFootprint = new UserFootprint();
        userFootprint.setUserId(sysUser.getUserId());
        userFootprint.setSiteUrl(url);
        userFootprint.setSiteName(siteInfo.getSiteName());
        userFootprint.setSiteLogo(logo);
        userFootprint.setDelTag("0");
        userFootprint.setCreateTime(System.currentTimeMillis());
        userFootprint.setUpdateTime(System.currentTimeMillis());

        userFootprintServiceClient.footprintSave(userFootprint);

        return sysUser;
    }

    @PostMapping("update")
    public ResultDataStruct<SysUser> update(@ModelAttribute SysUser sysUser) throws Exception {
        ResultDataStruct<SysUser> resultDataStruct = userInfoServiceClient.update(sysUser);

        if (resultDataStruct.getCode() != 200)
            throw new CustomException(UserExceptionEnum.getEnumByCode(resultDataStruct.getCode()));

        return resultDataStruct;
    }

    @PostMapping("updatePhone")
    public void updatePhone(@ModelAttribute SysUser sysUser, String code) throws Exception {
        UserParameterDataStruct<SysUser, String> userParameterDataStruct = new UserParameterDataStruct<>();
        userParameterDataStruct.setData(sysUser);
        userParameterDataStruct.setCode(code);

        if (Objects.isNull(sysUser) || StringUtils.isEmpty(sysUser.getPhone()))
            throw new CustomException(UserExceptionEnum.USER_PHONE_IS_NULL);

        SysUser exists = userCenterServiceClient.exists(sysUser).getData();

        if (Objects.nonNull(exists))
            throw new CustomException(UserExceptionEnum.PHONE_BE_USED);

        ResultMessageStruct resultMessageStruct = userInfoServiceClient.userinfoUpdatePhone(userParameterDataStruct);

        if (resultMessageStruct.getCode() != 200)
            throw new CustomException(UserExceptionEnum.getEnumByCode(resultMessageStruct.getCode()));
    }

    @PostMapping("updateEmail")
    public void updateEmail(@ModelAttribute SysUser sysUser) {

    }
}
